package cn.zzf.leetcode;

import java.util.LinkedList;

/**
 * 给你链表的头节点 head ，每 k 个节点一组进行翻转，请你返回修改后的链表。
 * <p>
 * k 是一个正整数，它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍，那么请将最后剩余的节点保持原有顺序。
 * <p>
 * 你不能只是单纯的改变节点内部的值，而是需要实际进行节点交换。
 *
 *
 * <pre>{@code
 * 示例 1：
 * 输入：head = [1,2,3,4,5], k = 2
 * 输出：[2,1,4,3,5]
 *
 * 示例 2：
 * 输入：head = [1,2,3,4,5], k = 3
 * 输出：[3,2,1,4,5]
 *
 * 提示：
 * 链表中的节点数目为 n
 * 1 <= k <= n <= 5000
 * 0 <= Node.val <= 1000
 *
 * 进阶：你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗？
 * }</pre>
 *
 * @author zzf
 */
public class T0025_ReverseKGroup {
    public static ListNode reverseKGroup1(ListNode head, int k) {
        if (head == null || head.next == null || k == 1) return head;

        LinkedList<ListNode> list = new LinkedList<>();

        ListNode tmp = head;
        int tmpVal;

        while (tmp != null) {
            for (int i = 1; i <= k; i++) {
                if (tmp == null) return head;
                list.addFirst(tmp);
                tmp = tmp.next;
            }

            while (!list.isEmpty()) {
                if (list.size() == 1) {
                    list.poll();
                    break;
                }
                tmpVal = list.peekFirst().val;
                list.pollFirst().val = list.peekLast().val;
                list.pollLast().val = tmpVal;
            }
        }
        return head;
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode hair = new ListNode(-1);
        hair.next = head;
        ListNode subHead = hair;
        ListNode subEnd = head;
        ListNode nextHead = head;
        while (nextHead != null) {
            ListNode pre = subHead;
            subHead = nextHead;
            //找到k长链表尾
            for (int i = 0; i < k; i++) {
                if (nextHead == null) {
                    pre.next = subHead;
                    return hair.next;
                }
                nextHead = nextHead.next;
            }
            subEnd = reverse(subHead, k);
            pre.next = subEnd;
        }
        return hair.next;

    }

    public static ListNode reverse(ListNode head, int k) {
        ListNode pre = null;
        ListNode cur = head;
        int i = 0;
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
            if (++i == k) {
                return pre;
            }
        }
        return pre;
    }


    public static void main(String[] args) {
        System.out.println(reverseKGroup(ListNode.of(1, 2), 2));
        System.out.println(reverseKGroup(ListNode.of(1, 2, 3, 4, 5), 2));
        System.out.println(reverseKGroup(ListNode.of(1, 2, 3, 4, 5, 6, 7), 4));
        System.out.println(reverseKGroup(ListNode.of(1, 2, 3, 4, 5), 3));
        System.out.println(reverseKGroup(ListNode.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13, 14, 16, 17), 8));
    }
}
